/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.krossk.servlets;

import br.com.krossk.dao.AreaDAO;
import br.com.krossk.dao.SegmentoDAO;
import br.com.krossk.jpa.JPAFactory;
import br.com.krossk.jspControllers.Menu;
import br.com.krossk.model.Area;
import br.com.krossk.model.Arquivo;
import br.com.krossk.model.PalavraChave;
import br.com.krossk.model.Repositorio;
import br.com.krossk.model.Usuario;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Henrique
 */
public class UploadServlet extends HttpServlet {

    HttpServletRequest request;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        /*response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
             //TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>UploadServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet UploadServlet at " + request.getContextPath () + "</h1>");
            out.println("<h2>Exceção : requisição GET</h2>");
            out.println("</body>");
            out.println("</html>");

        } finally {
            out.close();
        }*/
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        this.request = request;
        doUpload(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    protected void doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(ServletFileUpload.isMultipartContent(request)){

            //Objetos Upload
            FileItemFactory factory = new DiskFileItemFactory(1000, new File("C:\\Temp"/*getInitParameter("bufferPath")*/));

            //set : caminho temporário onde que o arquivo será armazenado durante o processo de upload
            

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(1024*1024*1024);

            Map<String, Object> hm = new HashMap<String, Object>();
            List<Area> areas = new ArrayList<Area>();
            FileItem fi = null;
            
            try {

                List <FileItem> items = upload.parseRequest(request);


                Iterator iter = items.iterator();

                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    
                    if(item == null){
                        continue;
                    }
                    if (item.isFormField()){
                        //Tratar itens do formulário, acão: armazenar na estrutura de Hashmap
                        if(item.getFieldName().indexOf("area") != -1)
                        {
                            Area a = AreaDAO.getInstance().getById(Integer.parseInt(item.getString()));
                            areas.add(a);
                        }
                        else
                        {
                            hm.put(item.getFieldName(), item.getString());
                        }

                    } else {
                        //Tratar arquivo
                        if(item.getName().length() > 0){
                            fi = item;
                        }else{
                            //Exceção - Nome do arquivo em branco
                            //response.sendRedirect("upload.jsp");
                            Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE,"Nome do arquivo em branco");
                        }
                    }

                }

                hm.put("areas", areas);

                // Inserir dados
                if(!items.isEmpty() && fi != null)
                    saveRequest(hm,fi);

                response.sendRedirect(Menu.ARQUIVO+"consulta.jsp");
            } catch (FileUploadException ex) {
                //response.sendRedirect("upload.jsp");
                Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE,ex.getMessage());
            }finally{

            }
        }
    }

    private void saveRequest(Map hm, FileItem fi)
    {
        HttpSession session = this.request.getSession();
        Usuario u =(Usuario) session.getAttribute("usuario");//(Usuario)session.getAttribute("usuario");
        Date dt = new Date();

        //Gravar informações no banco
        Arquivo arq = new Arquivo();

        String nome = fi.getName();

        if(nome.contains("\\"))
            arq.setNomeArquivo(nome.substring(nome.lastIndexOf("\\")+1));
        else
            arq.setNomeArquivo(nome);

        arq.setDataInclusao(dt);
        arq.setTitulo((String)hm.get("titulo"));
        arq.setAreaCollection((List<Area>)hm.get("areas"));
        arq.setSegmento(SegmentoDAO.getInstance().getById(Integer.valueOf((String)hm.get("segmento")))); //alterar
        arq.setPalavraChaveCollection((Collection<PalavraChave>) session.getAttribute("palavrasChave"));
        arq.setTipoArquivo(fi.getContentType());

        arq.setTamanho(fi.getSize());
        arq.setUsuario(u);
        
        EntityManager em = JPAFactory.getEntityManager();
        em.getTransaction().begin();
        em.persist(arq);
        Repositorio rep = new Repositorio(arq.getIdArquivo(), fi.get());
        em.persist(rep);
        em.getTransaction().commit();
        em.close();
    }    
}
